yjx.controller('orderController',['$rootScope','$scope','$stateParams','$fetch','$timeout','modalService','$state','$location',function($rootScope,$scope,$stateParams,$fetch,$timeout,modalService,$state,$location){
    //alert($location.url());
    var productId, activityId,
       type = $stateParams.type && $stateParams.type >1 ? $stateParams.type: 1,
        orderApi = '/productCenter/productDetail',/*获取产品详情*/
        getPrepayApi = '/WeiXinPay/uniformorder',
        clientId,
        pendingEventId;
    clientId = $stateParams.clientId;
    pendingEventId = $stateParams.pendingEventId;//$stateParams.pendingEventId
    if($stateParams.type && $stateParams.type>1){
        if($stateParams.type == 2){
            activityId = $stateParams.id;
        }
    }else{
        productId = $stateParams.id
    }
    //alert(productId);
    $scope.forward = {};
    $scope.forward.userId = $stateParams.forwardId;
    $scope.forward.nickname = $stateParams.forwardName;
    $scope.order = {};
    $scope.paySuc = false;
    $scope.payFail = false;

    $scope.editClient = {};
    $scope.sexes = [
        {id:1,value:'男'},
        {id:2,value:'女'}
    ];
    $scope.selectSex= function (id,value) {
        if($scope.editClient){
            $scope.editClient.sex=value;
        }else{
            $scope.editClient={};
            $scope.editClient.sex=value;
        }
    }


    /*获取单个产品订单内容*/
    function getOrder() {
        $fetch.fetch(
            orderApi,
            {
                params:{
                    productId:productId,
                    //userId:$rootScope.userId
                },
            }
        ).then(function(data){
                $timeout(function(){
                    if(data){
                        $scope.order = data.product
                        $scope.orders = [];
                        $scope.orders.push( $scope.order);
                        $scope.totalPrice = $scope.order.activityPrice? $scope.order.activityPrice: $scope.order.price;
                    }else{
                        modalService.mainMsgError("无法获取产品信息！");
                    }
                })
            }).catch(function(e){
                modalService.mainMsgError(e.msg)
            })
    }
    /*获取多个产品订单内容（通过活动id取得）*/
    function getOrders() {
        $fetch.fetch(
            '/activity/getBanners',
            {
                params:{
                    id:activityId
                },
            }
        ).then(function(data){
                $timeout(function(){
                    if(data && data.banners && data.banners.length > 0) {
                        $scope.data = data.banners[0];
                        if( $scope.data.productList){
                            $scope.orders = $scope.data.productList;
                            $scope.totalPrice = 0 ;
                            for(var i =0 ; i < $scope.data.productList.length;i++){
                                $scope.totalPrice = $scope.totalPrice + $scope.data.productList[i].activityPrice;
                            }
                        }


                    }else{
                        modalService.mainMsgError("无法获取产品信息！");
                    }
                })
            }).catch(function(e){
                modalService.mainMsgError(e.msg)
            })
    }
    if(!$stateParams.type || $stateParams.type == 1){
        getOrder();
    }else if ($stateParams.type == 2){
        getOrders();
    }

    /*获取客户信息*/
    if(clientId){
        $fetch.fetch(
            "/customer/getCustomer",
            {
                params:{
                    customerId:clientId,
                    userId:$rootScope.userId
                    //userId:$rootScope.userId
                },
            }
        ).then(function(data){
                $timeout(function(){
                    if(data){
                        $scope.editClient = data
                    }
                })

            }).catch(function(e){
                modalService.mainMsgError(e.msg)
            })
    }else{

    }


    /*微信支付*/
    $scope.getPrepay = function(){
        if(!$scope.editClient.sex){
            $scope.editClient.sex =  $scope.sexes[0].value
        }
        if(clientId){
            /*调用更新客户信息接口*/
            editClient();
        }
        //alert($scope.editClient);
        $fetch.fetch(
            getPrepayApi,
            {
                params:{
                    userId:$rootScope.userId,
                    productId:productId,
                    activityId:activityId,
                    inviterUserId: $stateParams.forwardId?$stateParams.forwardId:0,
                    pendingEventId:pendingEventId>0?pendingEventId:0,
                    customerName:$scope.editClient.customerName,
                    sex:$scope.editClient.sex,
                    age:$scope.editClient.age,
                    telephone:$scope.editClient.telephone,
                    address:$scope.editClient.address,
                    cardId:$scope.editClient.cardId,
                    type:type,
                }
            }
        ).then(function(data){
                $timeout(function(){
                    //alert("getPrepay")
                    chooseWXPay(data);
                })

            }).catch(function(e){
                if(e){
                    modalService.mainMsgError(e.msg)
                }else{
                    modalService.mainMsgError("服务器出错")
                }

            })
    }

    function chooseWXPay(data){
        function onBridgeReady(){
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId":data.appId,     //公众号名称，由商户传入
                    "timeStamp":data.timeStamp,         //时间戳，自1970年以来的秒数
                    "nonceStr":data.nonceStr, //随机串
                    "package":data.package,
                    "signType":data.signType,         //微信签名方式：
                    "paySign":data.paySign //微信签名
                },
                function(res){
                    //alert(res.err_msg)
                    if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                        //alert(res.err_msg)
                        $timeout(function(){
                            $scope.paySuc = true
                        })
                    }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                    else{
                        $scope.payFail = true
                    }
                }
            );
        }
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
            modalService.mainMsgInfo("请先关注基因团公众号<br>并在微信浏览器在中完成支付")
        }else{
            onBridgeReady();
        }
    }

     /*验证订单信息合法信*/
     $scope.editForm =function(){
        /*数据合法性验证*/
        console.log($scope.editClient)
        if(!$scope.editClient.customerName){
            modalService.mainMsgError("姓名必填")
            return
        }
        if(!$scope.editClient.age){
            modalService.mainMsgError("年龄必填")
            return
        }
        if(isNaN($scope.editClient.age)){
            modalService.mainMsgError("年龄必须是数字")
            return
        }
        if(!$scope.editClient.telephone){
            modalService.mainMsgError("手机号码必填")
            return
        }
        if(!$scope.editClient.telephone.match("^[1][34578][0-9]{9}$")){
            modalService.mainMsgError("请输入正确格式的手机号码")
            return
        }
        if(!$scope.editClient.address){
            modalService.mainMsgError("收货地址必填");
            return
        }
        if(!$scope.editClient.cardId) {
            modalService.mainMsgError("身份证号码必填");
            return
        }
        $scope.getPrepay();
    }

    /*编辑用户*/
    function editClient() {

        $fetch.fetch(
            '/customer/order/updateInfo',
            {
                params:{
                    userId:$rootScope.userId,
                    id:$scope.editClient.id,
                    customerName:$scope.editClient.customerName,
                    sex:$scope.editClient.sex,
                    age:$scope.editClient.age,
                    telephone:$scope.editClient.telephone,
                    address:$scope.editClient.address,
                    cardId:$scope.editClient.cardId,
                    //tagIds:$scope.selectedTags?$scope.selectedTags.join(','):null,
                },
                cache:false,
                type:'POST',
            }
        ).then(function(data){
            }).catch(function(e){
                //modalService.mainMsgError(e.msg);
            })
    }



    $scope.confirm =function(){
        if($scope.paySuc){
            $rootScope.tabCtrlName = $rootScope.tabCtrlNameArr[0];
            $state.go('index');
        }
        if($scope.payFail){
            history.back();
        }
    }
}])